﻿
using LeaderCCSLaserUI.Models;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Threading.Tasks;

namespace LeaderCCSLaserUI.Services
{
    public class GetBarcodeHttpService : IGetBarcodeService
    {
        #region 变量
        private HttpRestClient httpRestClient;
        #endregion
        public string[] Barcodes { get; set; }
        #region 功能函数
        public bool GetBarcode()
        {
            try
            {
                var str = httpRestClient.Execute(new BaseRequest { Method = Method.Get, Route = "" });
                str = str.Replace("\"", "");
                if (str != "Error")
                {
                    var bars = str.Split(new char[] { '|' });
                    if (bars.Length > 0)
                    {
                        Barcodes = new string[bars.Length];
                        for (int i = 0; i < Barcodes.Length; i++)
                        {
                            var strs = bars[i].Split(new char[] { ';' });
                            Barcodes[i] = strs[0].Replace(" ", string.Empty);
                        }
                        return true;
                    }
                    else
                    {
                        Barcodes = new string[4] { string.Empty, string.Empty, string.Empty, string.Empty };
                        return false;
                    }
                }
                else
                {
                    Barcodes = new string[4] { string.Empty, string.Empty, string.Empty, string.Empty };
                    return false;
                }
            }
            catch (Exception ex)
            {
                Barcodes = new string[4] { string.Empty, string.Empty, string.Empty, string.Empty };
                Debug.WriteLine(ex);
                return false;
            }

        }

        public void SetBarcode(string barcode, int product)
        {
            try
            {
                Barcodes[product] = barcode;
            }
            catch { }
        }
        #endregion
        #region 构造函数
        public GetBarcodeHttpService()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["BarcodeApiUrl"].ConnectionString;
            Barcodes = new string[4] { string.Empty, string.Empty, string.Empty, string.Empty };
            httpRestClient = new HttpRestClient(connectionString);
        }
        #endregion
    }
}
